var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('shipmentInfoCtrl', function($scope, $http) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
		httpPost($http, {"url":ctx + "/constractor/findListBy", "data": {"ffMap":{"st" : 0}}, "ifBlock" : true}, function(data){
			$scope.constractorList = data.dt;
		}, function(){
			toastError("初始化承运商列表失败。");
		});
		httpPost($http, {"url":ctx + "/vehicle/findListBy", "data": {"ffMap":{"st" : 0}}, "ifBlock" : true}, function(data){
			$scope.vehicleList = data.dt;
		}, function(){
			toastError("初始化运输工具列表失败。");
		});
		httpPost($http, {"url":ctx + "/driver/findListBy", "data": {"ffMap":{"st" : 0}}, "ifBlock" : true}, function(data){
			$scope.driverList = data.dt;
		}, function(){
			toastError("初始化司机列表失败。");
		});
		httpPost($http, {"url":ctx + "/dict/findListBy", "data": {"ffMap":{"cd" : "shipmentMethod", "st" : 0}}, "ifBlock" : true}, function(data){
			$scope.shipmentMethodList = data.dt;
		}, function(){
			toastError("初始化运输方式列表失败。");
		});
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "cd",
			displayName : "代码"
		},
		{
			field : "constractorName",
			displayName : "承运商"
		},
		{
			field : "vehicleCd",
			displayName : "车辆编码"
		},
		{
			field : "shipmentMethodName",
			displayName : "运输方式"
		},
		{
			field : "driverName",
			displayName : "司机"
		},
		{
			field : "vehicleTypeName",
			displayName : "车型"
		},
		{
			field : "volume",
			displayName : "体积"
		},
		{
			field : "weight",
			displayName : "额定载重"
		},
		{
			field : "descr",
			displayName : "描述"
		},
		{
			field : "st",
			displayName : "状态"
		}
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n: 'zh-cn', rowHeight : 21, footerRowHeight : 35,
		showFooter : true
	};

	$scope.query = function() {
		closeModal($("#queryFormModal"));
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/shipmentInfo/findListBy', "data" : requestBody, "ifBlock" : true}, function(data){
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
				if(data.dt.length === 0){
					toastWarning("没有找到符合查询条件的记录。");
				};
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//trigger query when currentPage not change
	$scope.onQuery = function(){
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};

	$scope.refresh=function(){
		hideShadow();
		$scope.onQuery();	
	};

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//crud
	$scope.onOpenQueryFormModal = function() {
		hideShadow();
		openModal($("#queryFormModal"));
		if($scope.queryForm == undefined){
			$scope.queryForm = {};
			$scope.queryForm.st = 0;
		}
	};
	
	//导出
	$scope.onOpenExportFormModal = function(){	
		var params;
		if($scope.queryForm == undefined){
			params="";
		}else{
			params = $scope.queryForm;
		}
		var str = jQuery.param(params);
		window.open(ctx  + '/shipmentInfo/export?' + str);
	};
	
	$scope.onOpenEditFormModal = function(type, id) {
		if(type == "add"){
			$scope.editForm = {};
			$scope.editForm.st = 0;
			$scope.editForm.shipmentMethod = 'TRUCK';
			$("#e").change(function(){
				var id = $scope.editForm.constractorId;
				httpGet($http, {"url":ctx + '/constractor/id/' + id, "ifBlock" : true}, function(data){	
					httpPost($http, {"url":ctx + "/vehicle/findListBy", "data": {"ffMap":{"constractorId" : id, "st" : 0}}}, function(data){
						$scope.vehicleList = data.dt;				
					}, function(){
						toastError("初始化承运商列表失败。");
					});
				});	
			});
				$("#vh").click(function(){
					var vid = $scope.editForm.vehicleId;
					httpGet($http, {"url":ctx + '/vehicle/id/' + vid, "ifBlock" : true}, function(data){
						$scope.editForm.driverId = data.dt['driverId'];
					}, function(){
						toastError("初始化运输工具列表失败。");
					});
				});
		}else if(type == "upd"){
			if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			httpGet($http, {"url":ctx + '/shipmentInfo/id/' + $scope.selectedRows[0]['id'], "ifBlock" : true}, function(data){
				$scope.editForm = data.dt;
				$("#e").change(function(){
					var id = $scope.editForm.constractorId;
					httpGet($http, {"url":ctx + '/constractor/id/' + id, "ifBlock" : true}, function(data){	
						httpPost($http, {"url":ctx + "/vehicle/findListBy", "data": {"ffMap":{"constractorId" : id,"st" : 0}}}, function(data){
							$scope.vehicleList = data.dt;				
						}, function(){
							toastError("初始化承运商列表失败。");
						});
					});	
				});
					$("#vh").click(function(){
						var vid=$scope.editForm.vehicleId;
						httpGet($http, {"url":ctx + '/vehicle/id/' + vid, "ifBlock" : true}, function(data){
							$scope.editForm.driverId = data.dt['driverId'];
						}, function(){
							toastError("初始化运输工具列表失败。");
						});
					});
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
		}
		hideShadow();
		openModal($("#editFormModal"));
	};
	$scope.onSaveEditForm = function(){
		closeModal($("#editFormModal"));
		httpPost($http, {"url":ctx + '/shipmentInfo/save', "data" : $scope.editForm, "ifBlock" : true}, function(data){
			toastSuccess("保存成功");
			$scope.query();
		}, function(errMsg){
			toastError("保存失败。" + errMsg);
		});
	};
	$scope.onOpenDelFormModal = function() {
		hideShadow();
		var selectedRowsLength = $scope.selectedRows.length;
		if(selectedRowsLength < 1) { toastWarning("请至少选择一笔记录进行删除。"); return; }
		dialogConfirm("是否确认删除选择的" + selectedRowsLength + "笔记录？", function(){
			var selectedRowsId = [];
			$.each($scope.selectedRows, function(idx, obj){
				selectedRowsId.push(obj.id);
			});
			httpPost($http, {"url":ctx + '/shipmentInfo/updStByIds', "params":{"ids" : selectedRowsId, "st" : 1}, "ifBlock" : true}, function(data){
				toastSuccess("删除成功");
				$scope.query();
			}, function(errMsg){
				toastError("删除失败。" + errMsg);
			});
		});
	};
	//右键菜单功能
	$('#mainDataBlock').contextMenu('menu', {
	      //菜单项样式
	      itemStyle: {
	        fontFamily : 'verdana',
	        backgroundColor : '#F0F0F0',
	        border: 'none',
	        padding: '4px'
	      },
	      //菜单项鼠标放在上面样式
	      itemHoverStyle: {
	        border: '1px solid #fff'
	      },
	      onShowMenu: function(e, menu) {
		    	if($scope.selectedRows.length === 0){
		          $('#del, #edit', menu).remove();
		        }else if($scope.selectedRows.length > 1){
		          if($scope.selectedRows[0]['st'] === 0){
		        	  $('#edit', menu).remove(); 
		          }else{
		        	  $('#edit,#del', menu).remove();
		          }		  
		        }else{
		        	 if($scope.selectedRows[0]['st'] === 1){
		        		 $('#del', menu).remove();
		        	 }
		        }
		        return menu;
		      }
		});
});